const xlsx = require('node-xlsx');
const fs = require('fs');
const { type } = require('os');

// 指定 HAR 文件路径
const harFilePath = 'www.jianshu.com.har';

// 读取 HAR 文件
const harData = fs.readFileSync(harFilePath, 'utf-8');
const harJson = JSON.parse(harData);

// 提取需要的数据
const entries = harJson.log.entries.map(entry => {
  return {
    name: getLastPartOfPath(entry.request.url),
    url: entry.request.url,
    mimeType: entry.response.content.mimeType,
    contentLength: bytesToSize(entry.response._transferSize),
    contentLengthByets:entry.response._transferSize,
    imgurl:entry.request.url
  };
});
console.log("获取数据完毕")
let pass={
  aes:true,
  images:false,
  JSON:false
}

let data=[
  {
    name:"head",
    data:[
      ["name","url","type","size","size(bytes)","img"]
    ]

  }
]

function getLastPartOfPath(path) {
  // 找到最后一个 '/' 的位置
  const lastSlashIndex = path.lastIndexOf('/');
  
  // 如果没有找到 '/', 返回整个字符串
  if (lastSlashIndex === -1) {
    return path;
  }

  // 截取从最后一个 '/' 后面的部分
  return path.substring(lastSlashIndex + 1);
}
for(k of entries){
  let a=null
  if(k.mimeType.startsWith('image')){
    a=`<table><img src="${k.imgurl}" width=30></table>`
  }
  if(k.name=='aes.1.1'&&pass.aes){
    continue
  }
  let mimeType=k.mimeType
  if(mimeType.slice(0,5)=='image'&&pass.images){
    continue
  }
  if(k.mimeType=='application/json'&&pass.JSON){
    continue
  }
  data[0].data.push([k.name,k.url,k.mimeType,k.contentLength,k.contentLengthByets,a])
}
function bytesToSize(bytes) {
  if (bytes === 0) return '0 B';
  var k = 1000, // or 1024
  sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
  i = Math.floor(Math.log(bytes) / Math.log(k));
  console.log("重新计算大小捏")
  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}

const buffer = xlsx.build(data);
fs.writeFileSync('test.xlsx', buffer);
console.log('done',`共有${entries.length}条数据`);